import axios from 'axios';
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth.ts';
import { useUserStore } from '@/store';

// 创建 Axios 实例
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 10000,
  withCredentials: true
});

// 添加请求拦截器
axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 全局响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    // 未登录
    if (data.code === 40100) {
      // 不是获取用户信息的请求，并且用户目前不是已经在用户登录页面，则跳转到登录页面
      if (
        !response.request.responseURL.includes('user/get/login') &&
        !window.location.pathname.includes('/login')
      ) {
        Message.warning('请先登录');
        window.location.href = `/login?redirect=${window.location.href}`;
      }
    }
    if (
      [50008, 50012, 50014].includes(data.code) &&
      response.config.url !== '/api/user/info'
    ) {
      Modal.error({
        title: '登录信息已过期',
        content: '登录信息已过期，请重新登录',
        okText: '去登录',
        async onOk() {
          const userStore = useUserStore();
          await userStore.logout();
          window.location.reload();
        }
      });
    }
    if (data.code === 40300) {
      window.location.href = `/exception/403`;
    } else if (data.code === 40400) {
      window.location.href = `/exception/404`;
    } else if (data.code === 50000) {
      window.location.href = `/exception/500`;
    }
    return data;
  },
  error => {
    Message.error({
      content: error.msg || '网络错误请稍后重试',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default request;
